<?php
class Admin_ItemController extends Zend_Controller_Action
{
static private $_indexes;

	public function init()
	{
        setlocale(LC_ALL, 'ru_RU.utf8');
		self::$_indexes = $this->getInvokeArg('bootstrap')->getOption('indexes');
	}
	public function preDispatch()
	{

    }
	public function indexAction()
	{
        $this->_helper->getHelper('jqgrid');
    }
	public function displayAction()
	{
		if($this->getRequest()->isPost())
		{
		$filters=array('id'=>array('HtmlEntities','StripTags','StringTrim'));
		$validators=array('id'=>array('NotEmpty','Int'));
		$url=$this->getRequest()->getRequestUri();
		$input=new Zend_Filter_Input($filters,$validators);
		$input->setData($this->getRequest()->getParams());
		if($input->isValid()){
			$q=Doctrine_Query::create()
				->from('Myblog_Model_Articles')
				->where('article_id=?',$input->id);
				if(!empty($q)){
					$result=$q->fetchArray();
					$this->view->headTitle('Статьи');
					$this->view->item=$result[0];
				}else{throw new Zend_Controller_Action_Exception('Page not found',404);}
				
			}else{throw new Zend_Controller_Action_Exception('Invalid input');}
		}else{throw new Zend_Controller_Action_Exception('Invalid input');}
	}

		public function createAction()
		{
			//$form=new Myblog_Form_ItemCreate();
		//	$this->view->form=$form;
				//if($this->getRequest()->isPost())
				//	{
				//	if($form->isValid($this->getRequest()->getPost())){
				//		$item=new Myblog_Model_Articles;
				//		$item->fromArray($form->getValues());
					
				//		$item->save();
				//		$q=Doctrine_Query::create()
				//			->from('Myblog_Model_Articles a')
				//			->select('a.article_id')
				//			->where('a.created_dt=?',$date)
				//			->fetchArray();
				//		$item->link='/catalog/item/display/'.$q[0]['article_id'];
				//		$item->save();
							
				//	self::createFulltextIndexAction();
						
				//		$this->_helper->getHelper('FlashMessenger')
				//			->addMessage('Новая статья добавлена!');
				//		$this->_redirect('/admin/catalog/item/success');
						
						
			//}
		//}
	    }

	public function deleteAction()
	{
		$filters=array('ids'=>array('HtmlEntities','StripTags','StringTrim'));
		$validators=array('ids'=>array('NotEmpty','Int'));
		$input=new Zend_Filter_Input($filters,$validators);
		$input->setData($this->getRequest()->getParams());
		if($input->isValid()){
			if(!empty($input->ids)){
			$q=Doctrine_Query::create()
				->delete('Myblog_Model_Articles a')
				->whereIn('a.article_id',$input->ids);
		$result=$q->execute();
		
		self::createFulltextIndexAction();
		
		$this->_helper->getHelper('FlashMessenger')
			->addMessage('Статья успешно удалена!');
		$this->_redirect('/admin/catalog/item/success');
		}else{
				$this->_helper->getHelper('FlashMessenger')
					->addMessage('Не выбраны статьи для удаления');
				$this->_redirect('/admin/catalog/item/success');
			 }	
		
	  }else{
			throw new Zend_Controller_Action_Exception('Invalid input');
			}	
	}

	public function updateAction()
	{
	$form=new Myblog_Form_ItemUpdate;
	$this->view->form=$form;

	if($this->getRequest()->isXmlHttpRequest())
	{
	$this->_helper->getHelper('layout')->disableLayout();
	$selectCat = $this->getRequest()->getPost('selectcat');
	
		if(!empty($selectCat) && $selectCat !=='')
		{
		$q=Doctrine_Query::create()
			->from('Myblog_Model_Articles a')
			->select('a.category_name')
			->fetchArray();
			if(!empty($q))
			{
			$select = array('select'=>$q[0]['category_name']);
			$this->_helper->json($select);	
			}
		
		}
	}

	if($this->getRequest()->isPost() && $form->isValid($this->_getAllParams())){
	$data=$this->getRequest()->getPost();
		if(!empty($data)){
		$q=Doctrine::getTable('Myblog_Model_Articles')
				->find($data['article_id']);
		$q->fromArray($data);
		}
		else{
			throw new Zend_Controller_Action_Exception('Invalid input');
			}
	$q->save();
	$this->_helper->getHelper('FlashMessenger')
		->addMessage('Статья успешно обновлена');
	$this->_redirect('/admin/catalog/item/success');
	}
	else{
$filters=array('id'=>array('HtmlEntities','StripTags','StringTrim'));
$validators=array('id'=>array('NotEmpty','Int'));
$input=new Zend_Filter_Input($filters,$validators);
$input->setData($this->getRequest()->getParams());

		if($input->isValid()){
		$q=Doctrine_Query::create()
			->from('Myblog_Model_Articles a')
			->where('article_id=?',$input->id);
		$result=$q->fetchArray();
		
			if(count($result)==1){
			
			$this->view->form->populate($result[0]);
			$this->view->item=$result[0];	
			}			
		}
	}
}	
	public static function createFulltextIndexAction()
	{
      //working
	//$this->_helper->getHelper('layout')->disableLayout();
	$q=Doctrine_Query::create()
		->from('Myblog_Model_Articles a')
		->where('a.visibility=?','yes');
	$result=$q->fetchArray();
	Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
	$config=self::$_indexes;
	$index=Zend_Search_Lucene::create($config['indexPath']);
		foreach($result as $r){
		$doc=new Zend_Search_Lucene_Document();
		$doc->addField(Zend_Search_Lucene_Field::Text('article',$r['article'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('title',$r['title'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('author',$r['author'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('category_name',$r['category_name'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::UnIndexed('article_id',$r['article_id'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('link',$r['link'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::UnIndexed('description',$r['description'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('created_dt',$r['created_dt'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Binary('img',$r['img'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('visibility',$r['visibility'],'UTF-8'));

		$index->addDocument($doc);
		}
		//$count=$index->count();
		//	$this->_helper->getHelper('FlashMessenger')
		//		->addMessage('Проиндексированы '.$count.' документов.');
		//	$this->_redirect('/admin/catalog/item/success');
	}	



	public function successAction()
	{

		if($this->_helper->getHelper('FlashMessenger')->getMessages()){
			$this->view->messages=$this->_helper
				->getHelper('FlashMessenger')->getMessages();
				//header("Refresh:3;/admin/index");
            $this->getResponse->setHeader('Refresh','3; URL=/admin/index');
			
			}else{
					$this->_redirect('/admin/index');
				 }
	}
    public function uploadAction(){


        if($this->getRequest()->isPost()){

            $this->_helper->getHelper('layout')->disableLayout();

            $error = "";
            $msg = "";
            $fileElementName = 'fileToUpload';
            if(!empty($_FILES[$fileElementName]['error']))
            {
                switch($_FILES[$fileElementName]['error'])
                {
                    case '1':
                        $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                        break;
                    case '2':
                        $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                        break;
                    case '3':
                        $error = 'The uploaded file was only partially uploaded';
                        break;
                    case '4':
                        $error = 'No_file_was_uploaded';
                        break;

                    case '6':
                        $error = 'Missing a temporary folder';
                        break;
                    case '7':
                        $error = 'Failed to write file to disk';
                        break;
                    case '8':
                        $error = 'File upload stopped by extension';
                        break;
                
                    default:
                        $error = null;
                }
            }elseif(empty($_FILES['fileToUpload']['tmp_name']) || 
             $_FILES['fileToUpload']['tmp_name'] == 'none'){
                $error = 'No_file_was_uploaded';
            }else{
            $upload = new Zend_File_Transfer();
            $upload->setValidators(array(
				        'Size'			=>array('min' => 5, 'max' => 1000000),
				        'Count' 		=>array('min' => 1, 'max' => 1),
				 //       'IsImage'=>array('jpeg','jpg','png','gif'),   getError
				        'ImageSize'=>array('minwidth'=>200,
				        									 'maxwidth'=>1920,
				        									 'minheight'=>100,
				        									 'maxheight'=>1080)
				        ));
            	//$width = $this->getRequest()->getPost('width');
            	//$height = $this->getRequest()->getPost('height');
            	if(!$upload->isValid()){
            		$this->_helper->json(array('status'=>'Downloading_Error'));
            		}
					//$uploaddir = "images/articles/";
					//$file = $_FILES['fileToUpload']['tmp_name'];
					$filename=pathinfo($upload->getFileName());
					$fileInfo = $upload->getFileInfo();
					$size = $upload->getFileSize();
					$newfilename=uniqid().'.'.$filename['extension'];

                $uploadAdp = new Zend_File_Transfer_Adapter_Http();
						if(isset($width) && isset($height)){
							$options = array('width' => $width, 'height' => $height);
						}else{
								$options = array('width' => 300, 'height' => 150);
						}

						$uploadAdp->addFilter(new Zend_Filter_File_ImageResize($options))
								//    ->addFilter('Rename',array('target'=>'images/articles/'.$newfilename,'overwrite'=>true))
                                    ->setDestination("images/articles/");
										
						if (!$uploadAdp->receive()){
										$this->_helper->json(array('status'=>'ImageResize_Error'));	
						}


                        @unlink($_FILES['fileToUpload']);

                            echo Zend_Json::encode(array("img"=>$filename['basename'] ));
                            //echo Zend_Json::encode(array("img"=>$newfilename  ));
				}
				if(!empty($error)){
                   echo Zend_Json::encode(array('upload_status'=>$error));

            	}
         }
    }
    public function getCategoriesAction(){

        if($this->getRequest()->isXmlHttpRequest()){
            $this->_helper->getHelper('layout')->disableLayout();
            $cat = Myblog_Model_Categories::getCategories();
            if($this->getRequest()->getParam('datatype')=='JSON'){
               // header('Content-type: application/json; charset=UTF-8');
              //  var_dump($cat);
                $this->_helper->json($cat);
            }
            $this->view->sel = $cat;
        }
    }
    public function setCategoriesAction(){
        if($this->getRequest()->isXmlHttpRequest()){
            $this->_helper->getHelper('layout')->disableLayout();
            $post = $this->getRequest()->getParams();
            $cat = Myblog_Model_Categories::setCategories($post);
            if($cat){$this->_helper->json(array('oper'=>$cat));}

        }
    }
    public function getPagesAction(){
        if($this->getRequest()->isXmlHttpRequest()){
            $this->_helper->getHelper('layout')->disableLayout();
            $pages = Myblog_Model_Pages::getPages();
            $this->view->pages = $pages;
        }
    }
}



